package pdf

import report.Activity;
import report.Plan;
import user.AuthController;

class PdfController extends AuthController {

	static allowedMethods = [plan: "POST", activities: "POST"]
	
	def pdfService                         
	        
	def plan = {
		if (params.id) {
			def plan = Plan.get(params.id)
			generate([type:"plan", output:plan])
		} else {
			flash.message = "Não foi possível gerar o relatório. Tente novamente!"
			redirect(controller: "plan", action: "list");
		}
	}
	
	def activities = {
		def activitiesList = []
		if (params.activities) {
			params.activities.each {
				activitiesList.add(Activity.get(it))
			}
			generate([type:"activities", output:activitiesList])
		} else {
			flash.message = "Não foi possível gerar o relatório. Tente novamente!"
			redirect(controller: "activity", action: "report");
		}
	}
	
	def generate = {
		try {
			byte[] b
			def baseUri = request.scheme + "://" + request.serverName + ":" + request.serverPort + grailsAttributes.getApplicationUri(request)
			def content = g.render(template:it.type, model:[pdf:it.output]).toString()
			b = pdfService.buildPdfFromString(content, baseUri)

			response.setContentType("application/pdf")
		    response.setHeader("Content-disposition", "attachment; filename=" + (params.filename ?: "document.pdf"))
		    response.setContentLength(b.length)
		    response.outputStream << b
	    } catch (Throwable e) {
	    	// grails problem, not ours.
	    }
	}
	                         
}
